<template>
  <div class="visitor-page">
    <!-- 用户信息头部 -->
    <div class="visitor-header">
      <div class="header-content">
        <!-- 返回按钮 -->
        <a-button 
          class="back-btn" 
          type="text" 
          @click="handleBack"
        >
          <template #icon>
            <ArrowLeftOutlined />
          </template>
          返回
        </a-button>
        
        <!-- 用户基本信息 -->
        <div class="user-info">
          <a-avatar :src="currentUserInfo.avatar" class="user-avatar" size="large" />
          <div class="user-details">
            <h2 class="user-name">{{ currentUserInfo.nickname || currentUserInfo.username || '未知用户' }}</h2>
            <p class="user-username">@{{ currentUserInfo.username }}</p>
            <div class="user-meta">
              <span v-if="currentUserInfo.email">{{ currentUserInfo.email }}</span>
              <span v-if="currentUserInfo.phone" class="sep">•</span>
              <span v-if="currentUserInfo.phone">{{ currentUserInfo.phone }}</span>
              <span v-if="currentUserInfo.deptName" class="sep">•</span>
              <span v-if="currentUserInfo.deptName">{{ currentUserInfo.deptName }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 内容标签页 -->
    <div class="content-tabs">
      <div class="main-tabs">
        <div
          v-for="tab in mainTabs"
          :key="tab.id"
          :class="['tab-item', { active: activeMainTab === tab.id }]"
          @click="selectMainTab(tab.id)"
        >
          {{ tab.name }}
        </div>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-display">
      <!-- 作品内容 -->
      <div v-if="activeMainTab === 'works'" class="works-content">
        <WorksManager 
          :works="works" 
          :loading="isLoading"
          :is-visitor-mode="true"
          @work-click="handleWorkView"
        />
      </div>

      <!-- 合集内容 -->
      <div v-else-if="activeMainTab === 'collections'" class="collections-content">
        <CollectionForVisitor 
          :collections="collections" 
          :loading="isLoading"
          @collection-click="handleCollectionView"
        />
      </div>
    </div>

    <!-- 合集详情弹窗 -->
    <CollectionDetail
      :collection-id="selectedCollectionId"
      v-model:visible="collectionDetailVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ArrowLeftOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { getUserById } from '@/api/user/sysUserController'
import { getWorksListByUserIdForVisitor } from '@/api/media/bizWorksController'
import { getCollectionList, getCollectionsByUserId } from '@/api/media/bizCollectionController'
import WorksManager from '@/components/profile/WorksManager.vue'
import CollectionForVisitor from '@/components/profile/CollectionForVisitor.vue'
import CollectionDetail from '@/components/profile/CollectionDetail.vue'

// 路由相关
const router = useRouter()
const route = useRoute()

// 获取用户ID参数
const userId = computed(() => Number(route.params.id))

// 状态管理
const isLoading = ref(false)
const currentUserInfo = ref<any>({})
const works = ref<any[]>([])
const collections = ref<any[]>([])

// 标签数据
const mainTabs = ref([
  { id: 'works', name: '作品' },
  { id: 'collections', name: '合集' }
])

const activeMainTab = ref('works')

// 合集详情相关
const selectedCollectionId = ref<number>(0)
const collectionDetailVisible = ref(false)

// 读取并标准化 MinIO 基础地址
const minioBaseUrl = ((import.meta as any).env?.VITE_MINIO_URL || '').replace(/\/$/, '')
const makeUrl = (p?: string) => {
  console.log('makeUrl input:', p, 'minioBaseUrl:', minioBaseUrl)
  if (!p) return ''
  if (/^https?:\/\//i.test(p)) return p
  const path = p.startsWith('/') ? p : `/${p}`
  const result = `${minioBaseUrl}${path}`
  console.log('makeUrl result:', result)
  return result
}

// 加载用户信息
const loadUserInfo = async () => {
  if (!userId.value) return
  
  try {
    isLoading.value = true
    console.log('开始加载用户信息，用户ID:', userId.value)
    
    const result = await getUserById({ id: userId.value })
    console.log('getUserById API响应:', result)
    
    if ((result as any).code === '00000' && result.data) {
      const userData = result.data as any
      console.log('原始用户数据:', userData)
      
      currentUserInfo.value = {
        id: userData.id,
        username: userData.username,
        nickname: userData.nickname,
        email: userData.email,
        phone: userData.phone,
        avatar: makeUrl(userData.filePath),
        deptName: userData.dept?.name
      }
      
      console.log('处理后的用户信息:', currentUserInfo.value)
    } else {
      console.error('API返回错误:', result)
      message.error('获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    message.error('获取用户信息失败')
  } finally {
    isLoading.value = false
  }
}

// 加载用户作品
const loadUserWorks = async () => {
  if (!userId.value) return
  
  try {
    isLoading.value = true
    console.log('开始加载用户作品，用户ID:', userId.value)
    
    const res = await getWorksListByUserIdForVisitor({ 
      id: userId.value, 
      name: '',
      status: 3
    })
    
    console.log('作品API响应:', res)
    
    if ((res as any).code === '00000' && res.data) {
      const worksData = (res as any).data || []
      console.log('原始作品数据:', worksData)
      
      // 确保数据是数组格式
      const worksList = Array.isArray(worksData) ? worksData : (worksData.list || [])
      
      works.value = worksList.map((work: any) => ({
        id: work.id,
        userId: work.userId,
        worksName: work.worksName,
        coverFileUrl: work.coverFileUrl,
        description: work.description || '暂无描述',
        tags: work.tags || '',
        isCharge: work.isCharge || 0,
        price: work.price || 0,
        status: work.status || 3,
        fileMd5: work.fileMd5 || '',
        createTime: work.createTime || '',
        updateTime: work.updateTime || '',
        deleted: work.deleted || 0
      }))
      
      console.log('处理后的作品数据:', works.value)
    } else {
      console.error('API返回错误:', res)
      works.value = []
    }
  } catch (error) {
    console.error('获取用户作品失败:', error)
    message.error('获取用户作品失败')
    works.value = []
  } finally {
    isLoading.value = false
  }
}

// 加载用户合集
const loadUserCollections = async () => {
  if (!userId.value) return
  
  try {
    isLoading.value = true
    console.log('开始加载用户合集，用户ID:', userId.value)
    
    const res = await getCollectionsByUserId({ 
      query: { 
        userId: userId.value, 
        status: 1,
        pageSize: 50 
      }
    })
    
    console.log('合集API响应:', res)
    
    if ((res as any).code === '00000' && res.data) {
      const collectionsData = (res as any).data.list || []
      console.log('原始合集数据:', collectionsData)
      
      collections.value = collectionsData.map((collection: any) => ({
        id: collection.id,
        userId: collection.userId,
        name: collection.name,
        coverUrl: collection.coverUrl || collection.coverFileUrl,
        description: collection.description || '暂无描述',
        status: collection.status || 1,
        createTime: collection.createTime || '',
        updateTime: collection.updateTime || ''
      }))
      
      console.log('处理后的合集数据:', collections.value)
    } else {
      console.error('API返回错误:', res)
      collections.value = []
    }
  } catch (error) {
    console.error('获取用户合集失败:', error)
    message.error('获取用户合集失败')
    collections.value = []
  } finally {
    isLoading.value = false
  }
}

// 标签切换
const selectMainTab = (tabId: string) => {
  activeMainTab.value = tabId
  if (tabId === 'works' && works.value.length === 0) {
    loadUserWorks()
  } else if (tabId === 'collections' && collections.value.length === 0) {
    loadUserCollections()
  }
}

// 返回
const handleBack = () => {
  router.back()
}

// 查看作品
const handleWorkView = (work: any) => {
  console.log('查看作品:', work)
  message.success(`查看作品: ${work.worksName}`)
  // 这里可以打开作品详情弹窗或跳转到详情页
}

// 查看合集
const handleCollectionView = (collection: any) => {
  console.log('查看合集:', collection.name)
  message.success(`查看合集: ${collection.name}`)
  
  // 设置选中的合集ID并打开详情弹窗
  selectedCollectionId.value = collection.id
  collectionDetailVisible.value = true
  
  console.log('打开合集详情弹窗，ID:', selectedCollectionId.value)
}

// 初始化
onMounted(async () => {
  if (!userId.value) {
    message.error('用户ID无效')
    router.push('/')
    return
  }
  
  await loadUserInfo()
  await loadUserWorks()
})
</script>

<style scoped>
.visitor-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
  color: #fff;
  padding-bottom: 40px;
}

.visitor-header {
  background: rgba(26, 26, 46, 0.9);
  backdrop-filter: blur(15px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.15);
  padding: 12px 24px;
}

.header-content {
  display: flex;
  align-items: center;
  max-width: 1400px;
  margin: 0 auto;
}

.back-btn {
  color: #ddd !important;
  margin-right: 16px !important;
  padding: 0 8px !important;
  font-size: 18px !important;
}

.back-btn:hover {
  color: #fff !important;
  background: rgba(255, 255, 255, 0.1) !important;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-avatar {
  border: 2px solid rgba(255, 255, 255, 0.1) !important;
  flex-shrink: 0;
}

.user-details {
  flex: 1;
}

.user-name {
  margin: 0 0 4px 0 !important;
  color: #fff !important;
  font-size: 24px !important;
  font-weight: 600 !important;
}

.user-username {
  margin: 0 0 8px 0 !important;
  color: #bbb !important;
  font-size: 16px !important;
}

.user-meta {
  color: #999;
  font-size: 14px;
  display: flex;
  gap: 8px;
  align-items: center;
}

.sep {
  opacity: 0.6;
}

.content-tabs {
  max-width: 1400px;
  margin: 24px auto 0;
  padding: 0 24px;
}

.main-tabs {
  display: flex;
  gap: 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.tab-item {
  padding: 12px 24px;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
  color: #ddd;
}

.tab-item:hover {
  color: #fff;
}

.tab-item.active {
  color: #ff4757;
  border-bottom-color: #ff4757;
}

.content-display {
  max-width: 1400px;
  margin: 24px auto 0;
  padding: 0 24px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #999;
  text-align: center;
}

.empty-icon {
  font-size: 48px;
  color: rgba(255, 255, 255, 0.2);
  margin-bottom: 16px;
}

@media (max-width: 768px) {
  .user-info {
    flex-direction: column;
    text-align: center;
  }
}
</style>
